//挂载vue实例，获取全局变量

import {apiUrl,tenantId} from '@/static/js/config';
import verify from './verify';

//单文件选择，一步到位（不推荐的方法）
export async function simpleUploadImg(url,data) {
	let [ err,res ] = await uni.chooseImage()
	console.log('chooseImage',err, res)
	if(!verify.null(res) && res.errMsg === 'chooseImage:ok'){
		let max = 10485760 //10M
		let size = res.tempFiles[0].size
		if(size < max){ // 不能大于10M
			return await upLoadImg(url,res.tempFilePaths[0],data)
		}else {
			throw new Error('ChooseImage Size Fail')
		}
	}
	else{
		throw new Error('ChooseImage Fail')
	}
}

//调用上传文件接口（使用起来比较灵活）
export function uploadImg(url:string,file:any,formData?:any) {	
	return new Promise((resolve,reject) => {
		uni.showLoading({
			title: '上传中...'
		})
		uni.uploadFile({
			url: apiUrl + url,
			filePath: file,
			name: 'file',
			header: {
				"Authorization": 'Bearer ' + uni.getStorageSync('accessToken'),
                'TENANT-ID': tenantId,
                'CLIENT-TOC': 'Y'
			},
			formData: formData,
			success: res => {
				// res.filePath = file;
                let {code, data,msg} = JSON.parse(res.data);
                if(code == '0'){
                    resolve(data)
                }else{
                    uni.$u.toast(msg);
                    reject(msg)
                }
			},
			fail: (err) => {
				console.log('uploadFile fail', err)
				reject()
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	})
}